<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>收费管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>


    <style>
        #feeType {
        width: 100px;
    }

    .layui-form-item .layui-inline {
        margin-right: 10px;
    }

    .layui-form-item .layui-input-inline {
        width: 150px;
    }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px ">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">费用类型</label>

                            <div class="layui-input-inline">
                                <select name="feeType" id="feeType" class="layui-input-inline">
                                    <option value="">请选择费用类型</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">居民名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">缴费状态</label>

                            <div class="layui-input-inline">
                                <select name="status" id="status" >
                                    <option value="">请选择缴费状态</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 批量删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>


    <!-- 编辑/添加弹窗 -->
    <div id="edit" style="display: none">
        <div class="layui-form layuimini-form" lay-filter="editForm">
            <div class="layui-form-item"  id="feeId"  >
                <label class="layui-form-label "  >费用ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="feeId" placeholder="请输入费用ID" readonly value="" class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item"  id="residentId"  style="display: none">
                <label class="layui-form-label "  >费用ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="residentId" placeholder="请输入费用ID" readonly value="" class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">费用类型</label>
                <div class="layui-input-inline">
                    <select name="feeType" id="feeType2" >
                        <option value="">请选择费用类型</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">金额</label>
                <div class="layui-input-inline">
                    <input type="number" name="amount" lay-verify="required" lay-reqtext="金额不能为空" placeholder="请输入金额" value="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">缴费截止日期</label>
                <div class="layui-input-inline">
                    <input type="text" name="dueDate" lay-verify="required" lay-reqtext="缴费截止日期不能为空" placeholder="请选择缴费截止日期" value="" class="layui-input" onclick="layui.laydate.render({elem: this})">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">居民</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" lay-verify="required" lay-reqtext="姓名不能为空" placeholder="请输入居民姓名" value="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required" >缴费状态</label>
                <div class="layui-input-inline">
<!--                    <input type="text" name="status" disabled lay-verify="required" lay-reqtext="缴费状态"  value="未缴费" class="layui-input" >-->
                    <select name="status" id="status2"   >
                        <option value="">请选择缴费状态</option>
                    </select>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
                </div>
                </div>
        </div>
    </div>

</div>

<!-- 状态标签模板 -->
<script type="text/html" id="statusTpl">
    {{# if(d.status == '已缴'){ }}
    <span class="layui-badge layui-bg-green">已缴</span>
    {{# } else if(d.status == '未缴'){ }}
    <span class="layui-badge layui-bg-yellow">未缴</span>
    {{# } }}
</script>

<!-- 费用类型模板 -->
<script type="text/html" id="feeTypeTpl">
    {{# if(d.feeType == '物业费'){ }}
    <span class="layui-badge layui-bg-orange">物业费</span>
    {{# } else if(d.feeType == '车位费'){ }}
    <span class="layui-badge layui-bg-blue">车位费</span>
    {{# } else if(d.feeType == '水费'){ }}
    <span class="layui-badge layui-bg-red">水费</span>
    {{# } else if(d.feeType == '电费'){ }}
    <span class="layui-badge layui-bg-green">电费</span>
    {{# } else if(d.feeType == '煤气费'){ }}
    <span class="layui-badge layui-bg-green">煤气费</span>
    {{# } }}

</script>

<script>

    layui.use(['form', 'table'], function () {

        var $ = layui.jquery;

        // 全局设置ajax请求头
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                //输出token
                console.log(data.token);
                if (data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });

        let  form = layui.form;
        let table = layui.table;
        // 全局设置ajax请求头
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                //输出token
                console.log(data.token);
                if (data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });

        let tag=-1; // 0 表示新增，1表示编辑
        // 加载科室、职务下拉框（模拟数据，实际应从接口获取）
        function loadSelectOptions(url, selectId) {
            $.getJSON(url, function (res) {
                if (res.code === 0 && res.data  ) {
                    var options = '';
                    res.data.forEach(function (item) {
                        options += `<option value="${item.id}">${item.value}</option>`;
                    });
                    $(selectId).append(options);
                    form.render('select');
                }
            });
        }

        loadSelectOptions('/fee/types', '#feeType');
        loadSelectOptions('/fee/status', '#status');
        loadSelectOptions('/fee/types', '#feeType2');
        loadSelectOptions('/fee/status', '#status2');




        table.render({
            elem: '#currentTableId',
            url: '/fee/all',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.message,
                    "count": res.count,
                    "data": res.data.list.map(item => {
                        const  payType =[ "","物业费", "车位费","水费","电费","煤气费"]
                        const  status=[ "", "已缴","未缴"]
                        const  paymentMethod=[ "", "微信", "支付宝"]

                        return {
                            ...item,
                            feeType: payType[item.feeType],
                            status: status[item.status],
                            paymentMethod: paymentMethod[item.paymentMethod]
                        }
                    })
                };
            },


            cols: [[
                {type: "checkbox", width: 50},
                {field: 'feeId', width: 100, title: '费用ID', sort: true},
                {field: 'feeType', width: 110, title: '费用类型', sort: true, templet: '#feeTypeTpl'},
                {field: 'amount', width: 100, title: '金额', sort: true},
                {field: 'dueDate', width: 200, title: '缴费截止日期', sort: true},
                {field: 'name', width: 180, title: '居民姓名', sort: true},
                {field: 'status', width: 80, title: '缴费状态', sort: true, templet: '#statusTpl'},
                {field: 'paidAt', width: 200, title: '缴纳时间', sort: true},
                {field: 'paymentMethod', width: 180, title: '缴费方式', sort: true},
                {field: 'residentId', width: 180, title: '居民ID', sort: true,hide: true},
                {title: '操作', minWidth: 100, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [ 10,15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line',
            response: {
                statusName: 'code',     // 对应后端状态码字段名
                statusCode: 0,           // 成功状态码
                msgName: 'message',      // 提示信息字段名
                countName: 'count', // 总条数字段路径
                dataName: 'data'    // 数据列表字段路径
            },

        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {

            table.reload('currentTableId', {
                page: {curr: 1},
                where: data.field
            }, 'data');
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {

            console.log( obj.data)
            if (obj.event === 'add') {  // 监听添加操作
                tag=0;// 表示新增
                var index = layer.open({
                    title: '添加费用',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['40%', '60%'],
                    content: $("#edit")
                });
                let  fee=$("#feeId")

                fee.hide(); // 确保新增时费用ID是显示的（或根据逻辑调整）

                form.val("editForm", {
                    "feeType": "",
                    "amount": "",
                    "dueDate": "",
                    "name": "",
                    "status": "待缴",
                    "paidAt": "",
                    "paymentMethod": "",
                });

                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                const  feeIds=data.map(item => item.feeId);

                $.ajax({
                    url: '/fee/deleteBatch',
                    type: 'POST',
                    contentType: 'application/json',  // 关键：声明发送 JSON
                    data: JSON.stringify(feeIds),  // 直接把数组序列化
                    dataType: 'json',
                    success: function (res) {
                        if (res.code === 0) {
                            layer.msg('删除成功');
                            table.reload('currentTableId');   // 重载表格
                        } else {
                            layer.msg(res.message || '删除失败');
                        }
                    },
                    error: function () {
                        layer.msg('网络异常');
                    }
                });


            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {

            console.log(obj,"@")
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                     tag=1;
                // 检查缴费状态是否为“已缴”
                if (data.status === '已缴') {
                    layer.msg('该费用记录已完成缴费，无法编辑！');
                    return false;
                }

                var index = layer.open({
                    title: '编辑费用',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['40%', '60%'],
                    content: $("#edit")
                });
                form.val("editForm", data);
                $("#feeId").show()


                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除行么', function (index) {

                    $.ajax({
                        url: '/fee/delete',
                        type: 'POST',
                        data: {feeId: data.feeId},
                        dataType: 'json',
                        success: function (res) {
                            if (res.code === 0) {

                                obj.del();
                                layer.msg('删除成功');
                                table.reload('currentTableId');   // 重载表格
                            } else {
                                layer.msg(res.message || '删除失败');
                            }
                        },
                        error: function () {
                            layer.msg('网络异常');
                        }
                    });

                    layer.close(index);
                });

            }
        });



        form.on('submit(saveBtn)', function (data) {
            var field = data.field;
            console.log( field,"edit")
            var url = tag===1 ? "/fee/update" : "/fee/add";

            console.log( field,"@22")
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(field),
                success: function (res) {
                    if (res.code === 0) {

                        layer.msg(tag===1 ? "更新成功" : "添加成功");
                        location.reload();
                    } else {
                        layer.msg(tag===1? "更新失败" : "添加失败");
                    }
                    layer.close(index);
                },
                dataType: "json"
            });

            return false;
        });
    });




</script>

</body>
</html>